package org.yuanqiframework.yuanqi.boot.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;
import org.yuanqiframework.yuanqi.web.auth.AuthContext;
import org.yuanqiframework.yuanqi.web.auth.service.LoginService;
import org.yuanqiframework.yuanqi.web.controller.BaseController;
import org.yuanqiframework.yuanqi.core.utils.captcha.ImageCaptcha;
import org.yuanqiframework.yuanqi.core.utils.captcha.ImageCaptchaUtils;
import org.yuanqiframework.yuanqi.web.entity.AjaxResult;
import org.yuanqiframework.yuanqi.web.entity.AjaxResultBuilder;
import org.yuanqiframework.yuanqi.boot.sys.dto.LoginUserDTO;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysUserDTO;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysUserPswDTO;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysUserQueryDTO;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysUser;
import org.yuanqiframework.yuanqi.boot.sys.service.ImageCaptchaService;
import org.yuanqiframework.yuanqi.boot.sys.service.SysUserService;
import org.yuanqiframework.yuanqi.boot.sys.vo.SysUserVO;
import org.yuanqiframework.yuanqi.boot.sys.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/sys/user")
public class UserController extends BaseController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private ImageCaptchaService imageCaptchaService;
    @Resource
    private LoginService loginService;


    @GetMapping("list")
    public AjaxResult<IPage<SysUserVO>> list(@Valid SysUserQueryDTO sysUserQueryDTO) {
        return success(sysUserService.listUser(sysUserQueryDTO));
    }

    //修改状态
    @PostMapping("updateStatus/{id}/{status}")
    public AjaxResult<?> updateStatus(@PathVariable String id, @PathVariable String status) {
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setStatus(status);
        return toAjax(sysUserService.updateById(sysUser));
    }

    //添加用户
    @PostMapping("save")
    public AjaxResult<?> save(@RequestBody @Valid SysUserDTO sysUserDTO) {
        return toAjax(sysUserService.saveUser(sysUserDTO));
    }


    @PostMapping("update/{id}")
    public AjaxResult<?> update(@PathVariable String id, @RequestBody @Valid SysUserDTO sysUserDTO) {
        return toAjax(sysUserService.updateUser(id, sysUserDTO));
    }


    //删除用户
    @PostMapping("delete/{id}")
    public AjaxResult<?> delete(@PathVariable String id) {
        log.info("删除用户：{}", id);
        SysUser user = sysUserService.getById(id);
        if (user == null) {
            return error("用户不存在");
        }
        if ("admin".equals(user.getUsername())) {
            return error("超级管理员不允许删除");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        return toAjax(sysUserService.removeById(sysUser));
    }

    @PostMapping("changePassword")
    public AjaxResult<?> changePassword(@RequestBody @Valid SysUserPswDTO sysUserPswDTO) {
        String userId = AuthContext.getUserId();
        return toAjax(sysUserService.changePassword(userId, sysUserPswDTO.getOldPassword(), sysUserPswDTO.getNewPassword()));
    }


    @GetMapping(value = "imageCaptcha")
    public AjaxResult<?> imageCaptcha(
            @RequestParam(required = false) Integer width,
            @RequestParam(required = false) Integer height
    ) throws IOException {
        Long timeout = 2L;
        ImageCaptcha captcha;
        // 生成验证码
        if (width != null && height != null) {
            captcha = imageCaptchaService.make(timeout, width, height,
                    ImageCaptchaUtils.default_codeCount,
                    ImageCaptchaUtils.default_thickness);
        } else {
            captcha = imageCaptchaService.make(timeout);
        }
        return AjaxResultBuilder.newInstance()
                .put("captchaKey", captcha.getKey())
                .put("captchaImage", captcha.getImage())
                .build();
    }


    @PostMapping(value = "login")
    public AjaxResult<UserInfoVO> login(@Valid @RequestBody LoginUserDTO loginUserDTO) {
        return AjaxResult.success(sysUserService.login(loginUserDTO));
    }


    @PostMapping(value = "logout")
    public AjaxResult<?> logout(HttpServletRequest request) {
        return toAjax(loginService.logout(request));
    }


}
